package com.daafan.minilib.http;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.util.Log;

public class BaseHttp {
	private static final String	TAG		= "BaseHttp";

	protected AjaxParams		params	= new AjaxParams();
	protected HttpHandler		handler;

	public void setParams(int page) {
		params.put("page", page + "");
	}

	public void req(final HttpHandler handler) {
		this.handler = handler;

		FinalHttp fh = new FinalHttp();
		String url = getUrl();
		fh.get(url, params, new AjaxCallBack<String>() {

			@Override
			public AjaxCallBack<String> progress(boolean progress, int rate) {
				if (handler != null)
					return handler.progress(progress, rate);

				return this;
			}

			@Override
			public void onStart() {
				if (handler != null) {
					handler.progressDialog();
					handler.onStart();
				}
			}

			@Override
			public void onLoading(long count, long current) {
				if (handler != null) {
					handler.onLoading(count, current);
				}
			}

			@Override
			public void onSuccess(String t) {
				Log.d(TAG, "onSuccess() : " + t);

				if (handler != null) {
					handler.cancelProgressDialog();
					handler.onSuccess(t);
					handler.onFinally();
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				Log.d(TAG, "onFailure() : Throwable = " + t.getMessage() + " strMsg = " + strMsg);

				if (handler != null) {
					handler.cancelProgressDialog();
					handler.onFailure(t, errorNo, strMsg);
					handler.onFinally();
				}
			}
		});
	}

	protected String getUrl() {
		return "";
	}

}
